package com.linkage.jz.bankruptcy.activity.Project.ZQUser.DetailOper;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.Project.ZQUser.ApplyChangeToMeActivity;
import com.linkage.jz.bankruptcy.adapter.FullyGridLayoutManager;
import com.linkage.jz.bankruptcy.base.BaseCreateActivity;
import com.linkage.jz.bankruptcy.bean.ApplyChangerZQUserNameBean;
import com.linkage.jz.bankruptcy.bean.TaskAtta;
import com.linkage.jz.bankruptcy.bean.ZQUserDetailBaseInfo;
import com.linkage.jz.bankruptcy.event.RefreshEvent;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.net.ToastUtil;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.jz.bankruptcy.widget.ApplyBaseReplyDialog;
import com.linkage.jz.bankruptcy.widget.CommonPromptDialog;
import com.linkage.jz.bankruptcy.widget.PublicNoticeDialog;
import com.linkage.jz.bankruptcy.widget.ShapeLoadingDialog;
import com.linkage.seapeak.pojo.UploadImage;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


/**
 * 变更债权人名称
 */
public class ApplyChangerLegalUserNameActivity extends BaseCreateActivity implements OnClickListener {
    private static final String TAG = ApplyChangerLegalUserNameActivity.class.getSimpleName();

    private RecyclerView mImgRecyclerView;

    private List<UploadImage> mImgList = new ArrayList<>();
    private GridImagesAdapter mImgAdapter;


    private TextView btn_commit, et_Name, et_Name_old;

    protected ShapeLoadingDialog mShapeLoadingDialog;
    private static int mType; //0审核，1查看

    private RecyclerView recyclerImgs;
    private List<UploadImage> imageList = new ArrayList<>();
    private GridImagesAdapter imgAdapter;


    private RecyclerView recyclerImgs_o;
    private List<UploadImage> imageList_o = new ArrayList<>();
    private GridImagesAdapter imgAdapter_o;


    @Override
    public void setListener() {

    }

    @Override
    public void initTitle() {
    }

    @Override
    public void initView() {

    }

    private ApplyBaseReplyDialog dialog;


    //    private static String mProID;
//    public static void start(Context context,MyProInfo info) {
//        Intent intent = new Intent(context, CreateProFlowActivity.class);
//        mInfo = info;
//        context.startActivity(intent);
//    }
    CommonPromptDialog mPromptDialog;
    private static ApplyChangerZQUserNameBean mInfo;

    public static void start(Context context, ApplyChangerZQUserNameBean info, int cType) {
        Intent intent = new Intent(context, ApplyChangerLegalUserNameActivity.class);
        mInfo = info;
        mType = cType;
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_apply_zq_legalusername);
        super.onCreate(savedInstanceState);
        titlebar_title = findViewById(R.id.top_title);

        if(mType == 0)
        {
            titlebar_title.setText("审核更改法定代表人");
        }else {
            titlebar_title.setText("更改法定代表人");
        }

        et_Name_old = findViewById(R.id.et_Name_old);
        et_Name = findViewById(R.id.et_Name);

        initViews();
        initData();

        recyclerImgs = findViewById(R.id.recycler_imgs);
        FullyGridLayoutManager manager = new FullyGridLayoutManager(this, 4, GridLayoutManager.VERTICAL, false);
        recyclerImgs.setLayoutManager(manager);
        imgAdapter = new BaseCreateActivity.GridImagesAdapter(ApplyChangerLegalUserNameActivity.this, TYPE_PREVIEW);
        imgAdapter.setList(imageList);
        recyclerImgs.setAdapter(imgAdapter);
        imgAdapter.setEnable(false);


        recyclerImgs_o = findViewById(R.id.recycler_imgs_old);
        FullyGridLayoutManager manager1 = new FullyGridLayoutManager(this, 4, GridLayoutManager.VERTICAL, false);
        recyclerImgs_o.setLayoutManager(manager1);
        imgAdapter_o = new BaseCreateActivity.GridImagesAdapter(ApplyChangerLegalUserNameActivity.this, TYPE_PREVIEW);
        imgAdapter_o.setList(imageList_o);
        recyclerImgs_o.setAdapter(imgAdapter_o);
        imgAdapter_o.setEnable(false);


        btn_commit = findViewById(R.id.btn_commit);
        if (mType == 0) {
            btn_commit.setVisibility(View.VISIBLE);
        } else {
            btn_commit.setVisibility(View.GONE);
        }

        if (mInfo != null) {


            if (mInfo.getChange() != null) {
                et_Name.setText(mInfo.getChange().getLegalRepresentativeName());
                if(mInfo.getChange().getProvideLegalRepresentativeChangeAttas()!=null) {
                    for (int i = 0; i < mInfo.getChange().getProvideLegalRepresentativeChangeAttas().size(); i++) {
                        TaskAtta atta = mInfo.getChange().getProvideLegalRepresentativeChangeAttas().get(i);
                        JSONObject obj = new JSONObject();
                        try {
                            obj.putOpt("filename", atta.getAttachmentName());
                            obj.putOpt("filepath", atta.getAttachmentDownloadAddress());
                            obj.putOpt("filesize", atta.getAttachmentSize());
                            obj.putOpt("loadUrl", atta.getAttachmentPreviewAddress());
                            imageList.add(new Gson().fromJson(obj.toString(), UploadImage.class));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }

            if (mInfo.getCreditorInfo() != null) {
                et_Name_old.setText(mInfo.getCreditorInfo().getLegalRepresentativeName());
                if(mInfo.getCreditorInfo().getProvidePowerAttorneyAttas()!=null) {
                    for (int i = 0; i < mInfo.getCreditorInfo().getProvideLegalRepresentativeAttas().size(); i++) {
                        TaskAtta atta = mInfo.getCreditorInfo().getProvideLegalRepresentativeAttas().get(i);
                        JSONObject obj = new JSONObject();
                        try {
                            obj.putOpt("filename", atta.getAttachmentName());
                            obj.putOpt("filepath", atta.getAttachmentDownloadAddress());
                            obj.putOpt("filesize", atta.getAttachmentSize());
                            obj.putOpt("loadUrl", atta.getAttachmentPreviewAddress());
                            imageList_o.add(new Gson().fromJson(obj.toString(), UploadImage.class));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }


        btn_commit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                dialog = new ApplyBaseReplyDialog(ApplyChangerLegalUserNameActivity.this, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (v.getId() == R.id.btn_save) {
                            String msg = dialog.text_reason.getText().toString().trim();
                            String status = "1";
                            if (dialog.cb_nopass.isChecked()) {
                                status = "2";
                            }
                            String notifyTypes = "";
                            if (dialog.send_msg.isChecked() && dialog.send_phone.isChecked()) {
                                notifyTypes = "0,1";
                            } else if (dialog.send_msg.isChecked()) {
                                notifyTypes = "0";
                            } else {
                                notifyTypes = "1";
                            }


//                    addZQUser(name,phone);
                            applyPerson(status, msg, notifyTypes);
                            dialog.dismiss();
                        }
                        if (v.getId() == R.id.btn_chancel) {
                            dialog.dismiss();
                        }

                    }
                });
                dialog.show();
            }
        });


    }


    private void initViews() {
        titlebar_back = findViewById(R.id.top_back1);
        titlebar_menu_text = findViewById(R.id.top_mune1);
        titlebar_menu_text.setOnClickListener(this);
        titlebar_back.setOnClickListener(this);
        titlebar_menu_text.setText("提交");
        titlebar_menu_text.setVisibility(View.INVISIBLE);
        et_Name = findViewById(R.id.et_Name);

//        FullyGridLayoutManager manager = new FullyGridLayoutManager(this, 4, GridLayoutManager.VERTICAL, false);
//        mImgRecyclerView = findViewById(R.id.recycler_imgs);
//        manager = new FullyGridLayoutManager(this, 4, GridLayoutManager.VERTICAL, false);
//        mImgRecyclerView.setLayoutManager(manager);
//        mImgAdapter = new GridImagesAdapter(this, TYPE_EDIT);
//        mImgAdapter.setList(mImgList);
//        mImgRecyclerView.setAdapter(mImgAdapter);

    }

    @Override
    public void initData() {

    }

    private boolean showflag = true;

//    @Override
//    public void onBackPressed() {
////        super.onBackPressed();
//        findViewById(R.id.titlebar_back).performClick();
//    }

    PublicNoticeDialog noticeDialog;

    @Override
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()) {

            case R.id.top_back1:
                noticeDialog = new PublicNoticeDialog(ApplyChangerLegalUserNameActivity.this, new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (v.getId() == R.id.btn_save_notice) {
                            ApplyChangerLegalUserNameActivity.super.finish();
                        }
                        noticeDialog.dismiss();
                    }
                }, 1, "提示", "放弃编辑？",
                        "否", "是");
                noticeDialog.show();
                break;
            case R.id.top_mune1:
//                saveData();
                break;
            default:
                break;
        }
    }


    /**
     * 保存信息
     */
    public void applyPerson(String status, String msg, String notifyTypes) {
        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
            return;
        }

        OkHttpClient okHttpClient = new OkHttpClient();
//        HashMap<String, String> params = new HashMap<String, String>();
        Random random = new Random();
        String rom = random.nextLong() + "";
        String timestamp = System.currentTimeMillis() + "";
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");
        String userId = SPUtils.getInstance(Consts.SPNAME).getString("userId", "");

//        String no = zqUserDetailInfo.get(0).getId();
        RequestBody requestBody = new FormBody.Builder()
                .add("appid", "1000000001")
                .add("nonce", rom)
                .add("timestamp", timestamp)
                .add("token", BankruptcyApp.tokeninfo.getToken())
                .add("userToken", userToken)
//                .add("creditorId", creditorId)
                .add("auditState", status)
                .add("auditDesc", msg)
                .add("noticeTypes", notifyTypes)
                .add("projectId", mInfo.getChange().getBankruptcyProjectId())
                .add("changeId", mInfo.getChange().getId())
                .add("auditType", "0")
                .build();

        String url = Consts.WEBURL_RIGHTSAUDIT;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
//                shapeLoadingDialog.dismiss();
//                Log.d(TAG, "onFailure: " + e.getMessage());
                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        //更新UI
                        Toast.makeText(ApplyChangerLegalUserNameActivity.this, "保存失败", Toast.LENGTH_SHORT).show();

                    }

                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
//                Log.d(TAG, response.protocol() + " " +response.code() + " " + response.message());
                Headers headers = response.headers();
//

                String str = response.body().string();
                try {
                    final JSONObject object = new JSONObject(str);
                    if (object.optInt("code") == 0) {
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI

                                com.linkage.seapeak.utils.ToastUtil.getInstance(ApplyChangerLegalUserNameActivity.this).showShortToast("审核成功");

                                finish();
//                                Toast.makeText(ApplyChangerZQUserNameActivity.this, "替吉奥成功", Toast.LENGTH_SHORT).show();

                            }

                        });
//                        finish();

                    } else {
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
                                Toast.makeText(ApplyChangerLegalUserNameActivity.this, "保存失败" + object.optString("msg"), Toast.LENGTH_SHORT).show();

                            }

                        });

                    }
                    str = "";
                } catch (Exception ex) {
                    ex.printStackTrace();
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            //更新UI
                            Toast.makeText(ApplyChangerLegalUserNameActivity.this, "保存失败", Toast.LENGTH_SHORT).show();

                        }

                    });
                }
            }
        });
    }

}

